package com.nbsaas.boot.app.rest.resource;

import com.nbsaas.boot.app.api.apis.AppMenuApi;
import com.nbsaas.boot.app.api.domain.request.AppMenuRequest;
import com.nbsaas.boot.app.api.domain.request.AppMenuSearch;
import com.nbsaas.boot.app.api.domain.response.AppMenuResponse;
import com.nbsaas.boot.app.api.domain.simple.AppMenuSimple;
import com.nbsaas.boot.app.data.entity.AppMenu;
import com.nbsaas.boot.app.data.repository.AppMenuRepository;
import com.nbsaas.boot.app.rest.convert.AppMenuEntityConvert;
import com.nbsaas.boot.app.rest.convert.AppMenuResponseConvert;
import com.nbsaas.boot.app.rest.convert.AppMenuSimpleConvert;
import com.nbsaas.boot.jpa.data.core.BaseResource;
import com.nbsaas.boot.rest.request.PageRequest;
import com.nbsaas.boot.rest.response.ListResponse;
import com.nbsaas.boot.rest.utils.TreeUtils;
import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.function.Function;

/**
 *   菜单-业务接口实现
 */
@Transactional
@Service
public class AppMenuResource extends BaseResource<AppMenu, AppMenuResponse, AppMenuSimple, AppMenuRequest> implements AppMenuApi {

    @Resource
    private AppMenuRepository appMenuRepository;

    @Override
    public JpaRepositoryImplementation<AppMenu, Serializable> getJpaRepository() {
        return appMenuRepository;
    }

    @Override
    public Function<AppMenu, AppMenuSimple> getConvertSimple() {
        return new AppMenuSimpleConvert();
    }

    @Override
    public Function<AppMenuRequest, AppMenu> getConvertForm() {
        return new AppMenuEntityConvert();
    }

    @Override
    public Function<AppMenu, AppMenuResponse> getConvertResponse() {
        return new AppMenuResponseConvert();
    }


    @Transactional(readOnly = true)
    @Override
    public ListResponse<AppMenuSimple> list(PageRequest request) {
        AppMenuSimpleConvert convert = new AppMenuSimpleConvert();
        if (request instanceof AppMenuSearch) {
            AppMenuSearch searchRequest = (AppMenuSearch) request;
            convert.setFetch(searchRequest.getFetch());
        }
        return listSimple(request, convert);
    }


    @Transactional(readOnly = true)
    @Override
    public ListResponse<AppMenuSimple> root(AppMenuSearch search) {
        ListResponse<AppMenuSimple> result = new ListResponse<>();
        List<AppMenuSimple> simples = list(search).getData();
        result.setData(TreeUtils.tree(simples));
        return result;
    }


}


